package com.sann.demo.dao.impl;

import com.sann.demo.dao.IAccountDao;
import com.sann.demo.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Repository
public class AccountDaoImpl implements IAccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> list = jdbcTemplate.query(
                "select * from tb_account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class),
                1);
        return CollectionUtils.isEmpty(list)?null:list.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> list = jdbcTemplate.query(
                "select * from tb_account where name like ?",
                new BeanPropertyRowMapper<Account>(Account.class),
                "%" + accountName + "%");
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        if(list.size()>1) {
            throw new RuntimeException("结果集不唯一");
        }
        return list.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        jdbcTemplate.update(
                "update tb_account set name=?, money=? where id=?",
                account.getName(), account.getMoney(), account.getId());
    }
}
